package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.OrderDAO;
import it.unibz.ti2.internetPizzeria.dao.ProductDAO;
import it.unibz.ti2.internetPizzeria.dao.UserDAO;

import it.unibz.ti2.internetPizzeria.entities.Customer;
import it.unibz.ti2.internetPizzeria.entities.Pizza;
import it.unibz.ti2.internetPizzeria.entities.Drink;
import it.unibz.ti2.internetPizzeria.entities.Delivery;
import it.unibz.ti2.internetPizzeria.entities.Order;
import it.unibz.ti2.internetPizzeria.entities.OrderProduct;

import it.unibz.ti2.internetPizzeria.utils.ServletUtil;
import it.unibz.ti2.internetPizzeria.webAttributes.UserInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Saving information about order to database and showing confirmation
 */
public class NewOrderConfirmation2 extends HttpServlet {

	private static final long serialVersionUID = -647408377383398736L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ProductDAO productDAO = null;
		try {
			productDAO = new ProductDAO();
			productDAO.openSession();
			UserDAO userDAO = new UserDAO();
			userDAO.openSession(productDAO);
			OrderDAO orderDAO = new OrderDAO();
			orderDAO.openSession(productDAO);

			Order order = new Order();
			Delivery delivery = new Delivery();

			Map<Pizza, Integer> pizzasMap = new TreeMap<Pizza, Integer>();
			Map<Drink, Integer> drinksMap = new TreeMap<Drink, Integer>();

			String[] pizzasIds;
			if (request.getParameterValues("pizzasIds") != null) {
				pizzasIds = request.getParameterValues("pizzasIds");
				for (int i = 0; i < pizzasIds.length; i++) {
					Integer quantity = new Integer(request
							.getParameter("numberOfPizzas" + pizzasIds[i]));
					if (quantity != 0) {
						Pizza pizza = productDAO.getPizza(Integer
								.parseInt(pizzasIds[i]));
						pizzasMap.put(pizza, quantity);
					}
				}
			}

			String[] drinksIds;
			if (request.getParameterValues("drinksIds") != null) {
				drinksIds = request.getParameterValues("drinksIds");
				for (int i = 0; i < drinksIds.length; i++) {
					Integer quantity = new Integer(request
							.getParameter("numberOfDrinks" + drinksIds[i]));
					if (quantity != 0) {
						Drink drink = productDAO.getDrink(Integer
								.parseInt(drinksIds[i]));
						drinksMap.put(drink, quantity);
					}
				}
			}

			UserInfo userInfo = (UserInfo) request.getSession().getAttribute(
					"userInfo");

			if (userInfo.getUserType().equals("Customer")) {
				Customer customer = (Customer) userDAO
						.getUser(userInfo.getId());
				if (customer != null) {
					String name = request.getParameter("userName");
					request.setAttribute("name", name);
					String surname = request.getParameter("userSurname");
					request.setAttribute("surname", surname);
					String city = request.getParameter("userCity");
					request.setAttribute("city", city);
					String streetAndNumber = request
							.getParameter("userStreetAndNumber");
					request.setAttribute("streetAndNumber", streetAndNumber);
					String country = request.getParameter("userCountry");
					request.setAttribute("country", country);
					String zipCode = request.getParameter("userZipCode");
					request.setAttribute("zipCode", zipCode);

					request.setAttribute("isCustomer", new Boolean(true));

					Float sumPrice = Float.parseFloat(request
							.getParameter("sumPrice"));
					request.setAttribute("sumPrice", sumPrice);

					Float productsPrice = Float.parseFloat(request
							.getParameter("productsPrice"));
					request.setAttribute("productsPrice", productsPrice);

					Float deliveryPrice = Float.parseFloat(request
							.getParameter("deliveryPrice"));
					request.setAttribute("deliveryPrice", deliveryPrice);

					request.setAttribute("pizzasMap", pizzasMap);
					request.setAttribute("drinksMap", drinksMap);

					Float pointLat = Float.parseFloat(request
							.getParameter("pointLat"));
					Float pointLng = Float.parseFloat(request
							.getParameter("pointLng"));

					delivery.setCity(city);
					delivery.setStreetAndNumber(streetAndNumber);
					delivery.setCountry(country);
					delivery.setZipCode(zipCode);
					delivery.setCharge(deliveryPrice);
					delivery.setPositionLat(pointLat);
					delivery.setPositionLng(pointLng);

					List<OrderProduct> orderProductsList = new ArrayList<OrderProduct>();
					for (Map.Entry<Pizza, Integer> entry : pizzasMap.entrySet()) {
						OrderProduct orderProduct = new OrderProduct();
						orderProduct.setOrder(order);
						orderProduct.setProduct(entry.getKey());
						orderProduct.setQuantity(entry.getValue());
						orderProductsList.add(orderProduct);
					}

					// List<OrderProduct> orderDrinksList = new
					// ArrayList<OrderProduct>();
					for (Map.Entry<Drink, Integer> entry : drinksMap.entrySet()) {
						OrderProduct orderProduct = new OrderProduct();
						orderProduct.setOrder(order);
						orderProduct.setProduct(entry.getKey());
						orderProduct.setQuantity(entry.getValue());
						orderProductsList.add(orderProduct);
					}

					order.setOrderProducts(orderProductsList);
					order.setDelivery(delivery);
					order.setCustomer(customer);
					order.setStatus(Order.StatusAwaitingPreparation);
					order.setOrderedDate(new Date());

					orderDAO.saveOrder(order);
					
					ServletUtil.redirect(request, response,
							"/newOrderConfirmation2.jsp");
				} else {
					request.setAttribute("isCustomer", new Boolean(false));
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (productDAO != null) {
				productDAO.closeSession();
			}
		}

	}
}
